package com.ruoyi.media.mediaAccount.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.media.mediaAccount.domain.MediaAccount;
import com.ruoyi.media.mediaAccount.domain.bo.MediaAccountBo;
import com.ruoyi.media.mediaAccount.domain.vo.MediaAccountVo;
import com.ruoyi.media.mediaAccount.mapper.MediaAccountMapper;
import com.ruoyi.media.mediaAccount.service.IMediaAccountService;
import com.ruoyi.media.publishModelConfig.domain.MediaPublishModelConfig;
import com.ruoyi.media.publishModelConfig.service.IMediaPublishModelConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

import static com.ruoyi.media.mediaAccount.domain.bo.MediaAccountBo.SPHXD;

/**
 * 自媒体账号列
 *
 * @author dqw
 * @date 2023-03-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/media/mediaAccount")
public class MediaAccountController extends BaseController {

    private final IMediaAccountService iMediaAccountService;
    private final IMediaPublishModelConfigService mediaPublishModelConfigService;
    private final MediaAccountMapper mediaAccountMapper;



    /**
     * 查询自媒体账号列列表
     */
    @SaCheckPermission("media:mediaAccount:list")
    @GetMapping("/list")
    public TableDataInfo<MediaAccountVo> list(MediaAccountBo bo, PageQuery pageQuery) {
        return iMediaAccountService.queryPageList(bo, pageQuery);
    }


    /**
     * 绑定下级用户
     */
    @SaCheckPermission("media:mediaAccount:add")
    @PostMapping("/bindLowerUser")
    public R<?> bindLowerUser(@RequestBody MediaAccountBo bo) {
       List<Long> list =  Arrays.asList(bo.getIdList());
       if(list.size() > 0){
           for(Long id : list){
               MediaAccount mediaAccount = new MediaAccount();
               mediaAccount.setId(id);
               SysUser sysUser =  mediaAccountMapper.getLowerUser(bo.getLowerUserId());
               if(sysUser == null){
                   throw new RuntimeException("用户数据异常！");
               }
               mediaAccount.setLowerUserId(bo.getLowerUserId());
               mediaAccount.setLowerUsername(sysUser.getUserName());
               iMediaAccountService.updateById(mediaAccount);
           }
       }
        return R.ok("绑定成功！");
    }



    /**
     * 获取视频号小店账号
     */
    @SaCheckPermission("media:mediaAccount:list")
    @GetMapping("/getChannelsMall")
    public R<?> getChannelsMall() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        LambdaQueryWrapper<MediaAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MediaAccount::getPlatformCode,SPHXD);
        queryWrapper.eq(MediaAccount::getLoginStatus,1);
        queryWrapper.eq(MediaAccount::getCreateBy,loginUser.getUsername());
        return R.ok(iMediaAccountService.list(queryWrapper));
    }

    /**
     * 导出自媒体账号列列表
     */
    @SaCheckPermission("media:mediaAccount:export")
    @Log(title = "自媒体账号列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MediaAccountBo bo, HttpServletResponse response) {
        List<MediaAccountVo> list = iMediaAccountService.queryList(bo);
        ExcelUtil.exportExcel(list, "自媒体账号列", MediaAccountVo.class, response);
    }

    /**
     * 获取自媒体账号列详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("media:mediaAccount:query")
    @GetMapping("/{id}")
    public R<MediaAccountVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iMediaAccountService.queryById(id));
    }



    /**
     * 修改自媒体账号的登录状态
     *
     */
    @SaCheckPermission("media:mediaAccount:query")
    @GetMapping("/updateAccountStatus/{jsonData}")
    public R<?> updateAccountStatus(@NotNull(message = "参数不能为空")
                                     @PathVariable String jsonData) {
        JSONObject data = JSONObject.parseObject(jsonData); //账号需要修改的信息
        String id =   data.getString("id");
        int status =  data.getInteger("status");
        MediaAccount mediaAccount = iMediaAccountService.getById(id);
        if(mediaAccount == null){
            throw new RuntimeException("系统异常！");
        }
        mediaAccount.setLoginStatus(status);
        return R.ok(iMediaAccountService.updateById(mediaAccount));
    }


    /**
     * 新增自媒体账号列
     */
    @SaCheckPermission("media:mediaAccount:add")
    @Log(title = "自媒体账号列", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MediaAccountBo bo) {
        return toAjax(iMediaAccountService.addMediaAccount(bo));
    }

    /**
     * 修改自媒体账号列
     */
    @SaCheckPermission("media:mediaAccount:edit")
    @Log(title = "自媒体账号列", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MediaAccountBo bo) {
        return toAjax(iMediaAccountService.updateByBo(bo));
    }

    /**
     * 删除自媒体账号列
     *
     * @param ids 主键串
     */
    @SaCheckPermission("media:mediaAccount:remove")
    @Log(title = "自媒体账号列", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iMediaAccountService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    /**
     * 视频号账号保持登录
     */
    @GetMapping("/channelsKeepLogin")
    public void channelsKeepLogin() {
        iMediaAccountService.keepChannelsKeepLogin();
    }



    /**
     * 视频号发布模板保存
     */
    @PostMapping("/savePublishModel")
    public R<?> savePublishModel(@RequestBody MediaAccountBo mediaAccountBo){
        MediaPublishModelConfig mediaPublishModelConfig = new MediaPublishModelConfig();
        mediaPublishModelConfig.setFilePath(mediaAccountBo.getFilePath());
        mediaPublishModelConfig.setIsFileTitle(mediaAccountBo.getIsFileTitle());
        mediaPublishModelConfig.setUserId(mediaAccountBo.getUserId());
        mediaPublishModelConfig.setAccountId(mediaAccountBo.getId());
        mediaPublishModelConfig.setPlatform(mediaAccountBo.getPlatformCode());
        mediaPublishModelConfig.setId(mediaAccountBo.getId());
        mediaPublishModelConfig.setDescription(mediaAccountBo.getDescription());
        // 保存视频号发布模板
        if(mediaPublishModelConfigService.getById(mediaAccountBo.getId()) != null){
            mediaPublishModelConfigService.updateById(mediaPublishModelConfig);
        }else{
            mediaPublishModelConfigService.save(mediaPublishModelConfig);
        }
        return R.ok("模板保存成功！");
    }



}
